package com.atguigu.base;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class phone{
    //判断 干活 通知
    private int i=0;
    /*public synchronized void add() throws InterruptedException {
        while (i!=0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+"=="+ ++i);
        this.notifyAll();
    }
    public synchronized void sub() throws InterruptedException {
        while (i==0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+"=="+--i);
        this.notifyAll();
    }*/
    //V2 JUC新版，Lock + condition.await() + condition.signalAll()
    private final Lock lock =new ReentrantLock();
    private final Condition condition = lock.newCondition();
    public void add() throws InterruptedException {
        lock.lock();
        try {
            while (i!=0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"=="+ ++i);
                condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
    public void sub() throws InterruptedException {
        lock.lock();
        try {
            while (i==0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"=="+--i);
                condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
public class ConcurrentDemo {
    public static void main(String[] args) {
        phone p = new phone();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++) {
                    try {
                        p.add();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }, "A").start();
        new Thread(()-> {
                for (int i = 1; i <= 10; i++) {
                    try {
                        p.sub();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }, "B").start();
        new Thread(()-> {
            for (int i = 1; i <= 10; i++) {
                try {
                    p.add();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();
        new Thread(()-> {
            for (int i = 1; i <= 10; i++) {
                try {
                    p.sub();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();
    }
}
